<template>

  <a class="icon-btn mx-2 wh-full" @click="dialogTableVisible = true" title="account">
    <div class="i-carbon-user-avatar-filled wh-full" />
  </a>

  <el-dialog ref="loginP" v-model="dialogTableVisible" align-center center class="loginP shadow-lg login-container-dialog">

    <el-tabs v-if="signIn === '立即注册'" v-model="activeName"  class="demo-tabs" @tab-click="handleTabClick">

      <el-tab-pane  name="first">
        <template #label>
            <span class="text-2xl">短信登录</span>
        </template>

        <el-form ref="ruleFormRef1" :model="ruleForm" status-icon :rules="rules"  class="demo-ruleForm" label-position="top" size="large">

          <el-form-item prop="phone" >
            <el-input placeholder="手机号登录/注册" v-model="ruleForm.phone" type="text" autocomplete="off" />
          </el-form-item>

          <el-form-item prop="verificationCode">

              <div class="w-full m-0 relative">
                <el-input placeholder="验证码" v-model="ruleForm.verificationCode" type="password" autocomplete="off" />

                <button 
                  class="w-25 absolute top-0 right-0 border-l  rounded-1 disabled:opacity-60" :disabled="disabled"
                  @click.prevent="verification" >
                  <span class="text-ms antialiased font-semibold text-blue-400 ">{{yanzheng}}</span>
                </button>
              </div>
              
          
            
            
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" class="w-full" @click="submitVCodeLogin(ruleFormRef1)">登录</el-button>
            
          </el-form-item>
        </el-form>
        <div class="flex justify-between text-lg">
          <span class="font-thin text-sm hover:text-blue-400">忘记密码?</span>
          <span @click="toggleSignIn" class="cursor-pointer font-thin text-sm hover:text-blue-400">{{signIn}}</span>
        </div>

      </el-tab-pane>

      <el-tab-pane  name="second">
        <template #label>
          <span class="text-2xl">密码登录</span>
        </template>

        <el-form ref="ruleFormRef2" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm" label-position="top"
          size="large">
        
          <el-form-item prop="account">
            <el-input placeholder="手机号/邮箱" v-model="ruleForm.account" type="text" autocomplete="off" />
          </el-form-item>
        
          <el-form-item prop="password">
            <el-input placeholder="密码" v-model="ruleForm.password" type="password" autocomplete="off" />
          </el-form-item>
        
          <el-form-item>
            <el-button type="primary" class="w-full" @click="submitAccountLogin(ruleFormRef2)">登录</el-button>
        
          </el-form-item>
        </el-form>
        <div class="flex justify-between text-lg">
          <span class="font-thin text-sm hover:text-blue-400">忘记密码?</span>
          <span @click="toggleSignIn" class="cursor-pointer font-thin text-sm hover:text-blue-400">{{signIn}}</span>
        </div>

      </el-tab-pane>

      
    </el-tabs>

    <div v-if="signIn === '已有账户'">
        <div class="border-b-gray-500 border-b-2 text-blue-400 border-opacity-30 pb-2 mb-4 "><span class="text-2xl">账号注册</span></div>
        <el-form ref="ruleFormRef3" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm" label-position="top"
          size="large">
        
          <el-form-item prop="account">
            <el-input placeholder="手机号/邮箱" v-model="ruleForm.account" type="text" autocomplete="off" />
          </el-form-item>
        
          <el-form-item prop="password">
            <el-input placeholder="密码" v-model="ruleForm.password" type="password" autocomplete="off" />
          </el-form-item>

          <el-form-item prop="confirmPWD">
            <el-input placeholder="确认密码" v-model="ruleForm.confirmPWD" type="password" autocomplete="off" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" class="w-full" @click="submitSignIn(ruleFormRef3)">注册</el-button>
        
          </el-form-item>
        </el-form>
        <div class="flex justify-between text-lg">
          <span class="font-thin text-sm hover:text-blue-400">忘记密码?</span>
          <span @click="toggleSignIn" class="cursor-pointer font-thin text-sm hover:text-blue-400">{{signIn}}</span>
        </div>
    </div>


  </el-dialog>



</template>

<script lang="ts" setup>
import type { TabsPaneContext, FormInstance } from 'element-plus'
import { fetchRegister, fetchLogIn, fetchSendCode,fetchPhoneLogin } from '@/server'
import { resetData } from '@/utils/reset'


//表单
const ruleFormRef1 = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()
const ruleFormRef3 = ref<FormInstance>()
const ruleForm = reactive({
  phone: '',
  account:'',
  verificationCode: '',
  password:'',
  confirmPWD:'',
})

//注册登录切换
const signIn = ref('立即注册')
const toggleSignIn = ()=>{
  if(signIn.value === '立即注册'){
    signIn.value = '已有账户'
    resetData(ruleForm)
  }else{
    signIn.value = '立即注册'
    resetData(ruleForm)
  }
}


//模态框开关
const dialogTableVisible = ref(false)
//发出模态框开关
const utils = useUtilsStore()
utils.setDialogTableVisible(dialogTableVisible)

//tab框切换开关
const activeName = ref('first')
const handleTabClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

//验证码
let disabled = ref<boolean>(false)
let yanzheng = ref<string>("验证码")
let timer: NodeJS.Timeout
const verification = ()=>{
  console.log(ruleForm.phone);
  
  fetchSendCode({ phone: ruleForm.phone}).catch(()=>{

  })
  disabled.value = true
  let i:number = 90
  yanzheng.value = `${i}秒`

  timer = setInterval(() => {  
    i--
    yanzheng.value = `${i}秒`
    if(i<1){
      clearInterval(timer)
      yanzheng.value = `验证码`
      disabled.value = false
    } 
  }, 1000)
}




const validatePass = (rule: any, value: any, callback: any) => {
  const reg:RegExp = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
  if (value === '') {
    callback(new Error('手机号不能为空!'))
  } else if (!reg.test(value)){
    callback(new Error('手机号不符合格式!'))
  }else{
    callback()
  }
}

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('验证码不能为空!'))
  } else {
    callback()
  }
}

const validatePass3 = (rule: any, value: any, callback: any) => {
  //手机号正则
  const reg: RegExp = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
  //邮箱正则
  const reg2: RegExp = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
  if (value === '') {
    callback(new Error('账号不能为空!'))
  } else if (reg.test(value) || reg2.test(value)) {
    callback()
  } else  {
    callback(new Error('账号不符合格式!'))
  }
}

const validatePass4 = (rule: any, value: any, callback: any) => {
  //密码正则
  const passwordReg = /^[a-zA-Z0-9!@.?]{6,16}$/
  if (value === '') {
    callback(new Error('密码不能为空!'))
  } else if (!passwordReg.test(value)) {
    callback(new Error("密码为6-16位数字大小写字母及!@.?"))
  } else {
    callback()
  }
}

const validatePass5 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('确认密码不能为空!'))
  } else if (value !== ruleForm.password) {
    callback(new Error("两次密码不一致!"))
  } else {
    callback()
  }
}

const rules = reactive({
  phone: [{ validator: validatePass, trigger: 'change' }],
  verificationCode: [{ validator: validatePass2, trigger: 'change' }],
  account: [{ validator: validatePass3, trigger: 'change' }],
  password: [{ validator: validatePass4, trigger: 'change' }],
  confirmPWD:[{ validator: validatePass5, trigger: 'change' }]
})

//提交手机验证登录表单
const submitVCodeLogin = (formEl: FormInstance | undefined)=>{
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      const { phone, verificationCode } = ruleForm
      const formData = {
        phone,
        code:verificationCode
      }

      const data = await fetchPhoneLogin(formData)
      const auth = useAuthStore()
      auth.setAuth(true)
      auth.setUser(data.userInfo)
      auth.setToken(data.token)
      location.reload()

    } else {
      console.log('error submit!')
      return false
    }
  })

  
}
//提交账户登录表单
const submitAccountLogin = (formEl: FormInstance | undefined)=>{
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      const { account, password } = ruleForm
      const formData = {
        phone : account,
        password
      }

      const data = await fetchLogIn(formData)
      const auth = useAuthStore()
      auth.setAuth(true)
      auth.setUser(data.userInfo)
      auth.setToken(data.token)
      location.reload()

    } else {
      console.log('error submit!')
      return false
    }
  })
}

//提交注册表单
const submitSignIn = (formEl: FormInstance | undefined)=>{
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      const { account,password} = ruleForm
      const formData = {
        phone:account,
        password
      }
      try{
        const data = await fetchRegister(formData)
        console.log(data);
        signIn.value = '已有账户'
        resetData(ruleForm)
        ruleFormRef3.value?.resetFields()
      }catch(err){
        ruleFormRef3.value?.resetFields()
      }
        
    } else {
      console.log('error submit!')
      return false
    }
  })
}




</script>

<style lang="scss">
.login-container-dialog {
  border-radius: 4px !important;
  padding: 0 40px;
  box-shadow: 0 0 0 0.625rem #FDF2F8,0 0 0 1.125rem #FBCFE8;
  width: 25% !important;
  @media screen and (min-width:1280px) and (max-width:1536px) {
    width: 33% !important;
    padding: 0 32px;

  }
  @media screen and (min-width:1024px) and (max-width:1280px) {
    width: 40% !important;
    padding: 0 26px;
    
  }
  @media screen and (min-width:768px) and (max-width:1024px) {
    width: 50% !important;
    padding: 0 20px;

  }
  @media screen and (min-width:640px) and (max-width:768px) {
    width: 70% !important;
    padding: 0 16px;

  }
  @media screen and (max-width:640px) {
    width: 78% !important;
    padding: 0 8px;
    
  }
  @media screen and (max-width:500px) {
    width: 86% !important;
    padding: 0 2px;

  }
}
</style>
